<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';

function getSiteList($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/tongji/v1/ReportService/getSiteList', $header);
	if( !$doResponse ) {
		return;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return;
	}
	if( !isset($bodyArray['header']) ) {
		return;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return;
	}
	if( $bodyArray['header']['desc'] == 'success' ) {
		if(is_array($bodyArray['body']['data'])) {
			$siteArray = [];
			foreach ( $bodyArray['body']['data'][0]['list'] as $value ) {
				if( stripos($value['domain'], 'aisite.wejianzhan.com') === false ) {
					array_push($siteArray, $value['site_id']);
				}
			}
			$siteid = implode(',', $siteArray);
			$countRquota = $bodyArray['header']['rquota'];
			$database->query( " UPDATE cfg_expand SET `countStat` = 0, `countRquota` = '{$countRquota}', `countMessage` = '', `siteid` = '{$siteid}', `lastDatetime` = NOW() WHERE username = '{$user['username']}' ");
		}
	} else {
  	$countMessage = serialize(isset( $bodyArray['header']['failures'][0]) ?  $bodyArray['header']['failures'][0] : []);
		$database->query( " UPDATE cfg_expand SET `countStat` = 999, `countRquota` = 0, `countMessage` = '{$countMessage}', `siteid` = '', `lastDatetime` = NOW() WHERE username = '{$user['username']}' ");
	}
}

run(function() use ($argv) {
	showMessage('获取站点列表.' );

	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `userid`, `username`, `password`, `token` FROM cfg_expand where status = 1 and userType BETWEEN 1 AND 2');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}

	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'获取站点列表.' );
				getSiteList(json_encode(['header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'], 'account_type' => 1]]), $database, $user);
			});
		}
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');